// banner controller
const { code } = require('../utils/stateModel')
const Banner = require('../db/models/bannerSchema')
const pagerFun = require('../utils/pager')
const { successModel, errorModel } = require("../utils/stateModel")

// 首页 banner
const getBannerList = async (ctx, { pageNum, pageSize, ...params }) => {
  try {
    const query = Banner.find({}, 'imgUrl jumpUrl')
    const bannerList = await query.skip(pagerFun(pageNum, pageSize).skipIndex).limit(pagerFun(pageNum, pageSize).pager.pageSize)
    const total = await Banner.countDocuments(params)
    if (query) {
      return ctx.body = new successModel({
        bannerList: bannerList,
        total,
        errorMessage: "查询图片列表成功"
      })
    }
    return
  } catch (error) {
    ctx.body = new errorModel({
      bannerList: [],
      errorMessage: "查询图片列表失败"
    })
  }
}

// 更新、新增 Banner
const updateBannerList = async (ctx, { _id, action, ...params }) => {
  // banner 编辑某项
  if (action === 'edit') {
    try {
      const bannerItem = await Banner.findOneAndUpdate({ _id }, { ...params })
      if (bannerItem) {
        return ctx.body = new successModel("修改成功")
      }
      return ctx.body = new errorModel("修改失败")
    } catch (error) {
      return ctx.body = new errorModel(error.message)
    }
  } else {
    if (!params.jumpUrl || !params.imgUrl) {
      return ctx.body = new errorModel('参数错误', code.PARAM_ERROR)
    }
    try {
      const banner = await new Banner({
        bannerId: new Date().getTime(),
        ...params
      })
      await banner.save()
      ctx.body = new successModel('新增成功')
    } catch (error) {
      return ctx.body = new errorModel(error.message)
    }
  }
}

// 删除banner list
const deleteBannerList = async (ctx, { _id }) => {
  if (!_id) {
    return ctx.body = new errorModel("参数错误", code.PARAM_ERROR)
  }
  console.log(_id, '--------_id-------')
  try {
    const res = await Banner.deleteMany({ _id: { $in: _id } })
    console.log(res, '-------res---------')
    ctx.body = new successModel(`删除成功${res.deletedCount}条`)
    return
  } catch (error) {
    ctx.body = new errorModel("删除失败", code.DB_ERROR)
  }
}

module.exports = {
  getBannerList,
  updateBannerList,
  deleteBannerList
} 